package com.acooly.module.openapi.client.provider.webank.utils;

import com.acooly.core.utils.mapper.BeanMapper;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.cglib.beans.BeanMap;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import lombok.extern.slf4j.Slf4j;

/**
 * @author fufeng 2017/11/30 13:53.
 */
@Slf4j
public class MapHelper {

    private static Map<Class, List<String>> beanFieldListMap = new ConcurrentHashMap<>();

    /**
     * 转换bean成LinkedHashMap
     * @param source
     *
     * @return
     */
    public static LinkedHashMap toLinkedHashMap (Object source) {

        Map<String, Object> convertMap = BeanMapper.map(source, Map.class);
        LinkedHashMap resultMap = new LinkedHashMap ();
        List<String> properties = getProperties (source.getClass ());
        if (CollectionUtils.isEmpty (properties))
            return null;
        for (String field : properties) {
            resultMap.put (field, convertMap.get (field)==null ?"" :convertMap.get(field));
        }
        return resultMap;
    }

    /**
     * 将map装换为javabean对象
     * @param map
     * @param bean
     * @return
     */
    public static <T> T mapToBean(Map<String, Object> map,T bean) {
        BeanMap beanMap = BeanMap.create(bean);
        beanMap.putAll(map);
        return bean;
    }

    /**
     * 获取指定类的属性列表
     *
     * @param clz
     *
     * @return
     */
    public static List<String> getProperties (Class clz) {
        if (beanFieldListMap.containsKey (clz)) {
            return beanFieldListMap.get (clz);
        }
        Field[] fields = clz.getDeclaredFields ();
        clz.getFields ();
        List<String> properties = new ArrayList<>();
        for (int i = 0; i < fields.length; i++) {
            properties.add (fields[i].getName ());
        }
        beanFieldListMap.put (clz, properties);
        return properties;
    }





}
